<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*30);

require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
require_once dirname(__FILE__). '/util/TimeUtil.php';

$g_start = microtime(true);

$dbconn = Connection::getInstance();

if(count($argv) ==  2) {
	list($year, $month) = explode('_', date('Y_m', strtotime($argv[1])));
} else {
	list($year, $month) = explode('_', date('Y_m'));
}


//$year = '2011';
//$month = '11';
//$time = '2011_11';


$result = collectValuePerToken($year, $month);

echo formatVarianceResult($result, $year, $month);

function collectValuePerToken($year, $month) {
	chdir(RAW_DATA_ROOT . '/' . $year . '_' . $month);
	
	$valuePerToken = array();
	$varianceValuePerTokenByWeek = array();
	
	foreach (glob("*_*") as $filename) {
		
		if (count(explode('_', $filename)) == 2) {
			list($day, $hour) = explode('_', $filename);
			$week = date('W', strtotime($year . $month . $day));
			
			$handler = fopen(RAW_DATA_ROOT . '/' . $year . '_' . $month . '/' . $filename, 'r');
			if ($handler) {
				while (!feof($handler)) {
					$line = fgets($handler);
					if (!empty($line)) {
						$args = explode(':', $line);
						if (!empty($args[4]) && !empty($args[0]) && !empty($args[3]) && !empty($args[11]) && !empty($args[16]) && !empty($args[18])) {
							$event = $args[4];
							$uid = $args[3];
							$site = $args[11];
							$token = $args[18];
							$won = $args[16];
							
							if ($event == 'played' && $uid != 0 && $won != 0  && $token != 0) {
								$valuePerToken[$week][$site][] = $won/$token;
							}
							
						}
					}
				}
				fclose($handler);
			}
		}
		
		// When it start iterating another week , calculate last week's variance
		if (count($valuePerToken) > 1) {
			$lastWeek = $week - 1;
			foreach ($valuePerToken[$lastWeek] as $site => $valuePerTokenFilterBySite) {
				$varianceValuePerTokenByWeek[$site][$lastWeek] = getVariance(array_values($valuePerTokenFilterBySite));
				unset($valuePerToken[$lastWeek][$site]);
			}			
		}
	}
	
	// calculate the variance of the last week of this month
	if (isset($valuePerToken[$week]) && count($valuePerToken[$week]) > 0) {
		foreach ($valuePerToken[$week] as $site => $valuePerTokenFilterBySite) {
			$varianceValuePerTokenByWeek[$site][$week] = getVariance(array_values($valuePerTokenFilterBySite));
			unset($valuePerToken[$week][$site]);
		}
	}
	
	return $varianceValuePerTokenByWeek;
}


function getVariance(array $rawdata) {
		$totalNums = count($rawdata);
		$total = 0;
		foreach ($rawdata as $data) {
			$total += $data;
		}
		$avarage = $total / $totalNums;
		
		$varianceTotal = 0;
		foreach ($rawdata as $data) {
			$varianceTotal += pow(($data - $avarage), 2);
		}
		//echo $varianceTotal . ' -----  ' . $totalNums . '<br/>';
		return sprintf("%.2f", ($varianceTotal / $totalNums));
}

function formatVarianceResult(array $result, $year, $month) {
	$monthStart = date('Y-m-d', mktime(0, 0 , 0, $month, 1, $year));
	$monthEnd = date('Y-m-d', (mktime(0, 0 , 0, ($month + 1), 1, $year) - 100));
	$return = 'Variance of Value Per Token:' . "\n";
	
	foreach ($result as $site => $resultBySite) {
		$return .= "\n\n" . $site . "\n";
		$return .= "Start of Week\tEnd of Week\tVariance of Valuer Per Token\n";
		foreach ($resultBySite as $week => $weekResult) {
			$weekRange = TimeUtil::getStartAndEndDate($week, $year);
			if ($weekRange['start'] < $monthStart) {
				$weekRange['start'] = $monthStart;
			}
			if ($weekRange['end'] > $monthEnd) {
				$weekRange['end'] = $monthEnd;
			}
			$return .= $weekRange['start'] . '  ---  ' . $weekRange['end'] . "\t" . $weekResult . "\n";
		}
	}
	return $return;
}